package com.penghaisoft.microwms.material.web.outwarehouse.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import com.penghaisoft.microwms.common.data.model.RawRequisition;
import com.penghaisoft.microwms.common.data.model.RawRequisitionSn;
import com.penghaisoft.microwms.common.dto.HandResp;
import com.penghaisoft.microwms.common.dto.RawOrderOutDto;
import com.penghaisoft.microwms.common.dto.RawRequisitionMesDto;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.service.MesProperties;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.BaseDictionaryMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawStorageSnMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.dao.OutWhRawMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.dao.RawRequisitionSnMapper;
import com.penghaisoft.microwms.material.web.outwarehouse.service.OutWhRawService;

/**
 * Created by 王治国 on 2018/5/18.
 */
@Service
public class OutWhRawServiceImpl extends BaseService implements OutWhRawService {

    @Autowired
    private OutWhRawMapper outWhRawMapper;
    
    @Autowired
    private RawRequisitionSnMapper rawRequisitionSnMapper;
    
    @Autowired
    private RawStorageSnMapper rawStorageSnMapper;
    
    @Resource
	private BaseDictionaryMapper baseDictionaryMapper;
    
    @Resource
	private MesProperties mesProperties;


    @Override
    public Pager<RawRequisition> findAll(int page, int rows, RawRequisition rawRequisition) {
        long size = outWhRawMapper.queryCount(rawRequisition);
        Pager<RawRequisition> pager = new Pager<>();
        List<RawRequisition> result = new ArrayList<>();
        pager.setPage(page);
        pager.setRows(rows);
        if (size > 0) {
            result = outWhRawMapper.queryList(pager, rawRequisition);
            
            RawRequisition sumAmount = outWhRawMapper.querySumAmount(rawRequisition);
        	pager.setOrder("{\"requireAmount\":\"" + sumAmount.getRequireAmount() + "\",\"realAmount\":\"" + sumAmount.getRealAmount() + "\"}");
        }
        pager.setRecords(result);
        pager.setTotalCount(size);
        return pager;
    }
    
    /** 
     * @Title findList
     * @Description 根据领料单号查询数据
     * @author luoteng
     * @date 2018年7月3日:下午4:32:02
     * @param rawRequisition
     * @return TransResult
     */
    @Override
    public List<RawRequisition> findList(RawRequisition rawRequisition) {
        return outWhRawMapper.queryList(null, rawRequisition);
    }
    
    /** 
     * @Title findList
     * @Description 根据领料单号查询匹配信息
     * @author luoteng
     * @date 2018年7月3日:下午4:32:02
     * @param rawRequisition
     * @return TransResult
     */
    @Override
    public List<RawRequisitionSn> queryScanInfo(RawRequisitionSn t){
    	RawRequisitionSn rearchOb = new RawRequisitionSn();
    	rearchOb.setActiveFlag("1");
//    	领料单类型：0：普通（PE管匹配钢管）1：返修（PE管匹配自身长度） 2；管件（PE管匹配自身长度）
    	rearchOb.setRequisitionTypeNot("1");
    	rearchOb.setRequisitionNo(t.getRequisitionNo());
    	List<RawRequisitionSn> tmpList = rawRequisitionSnMapper.queryByAnyOrder(rearchOb);
    	if(tmpList != null && !tmpList.isEmpty()) {
    		if(tmpList.get(0).getRequisitionType() != null && tmpList.get(0).getRequisitionType().equals("0")) {
    			tmpList = rawRequisitionSnMapper.queryScanInfo(t);
    		}
    	}
    	
    	return tmpList;
    }

    @Override
    public List<RawRequisition> findAllExcel(RawRequisition rawRequisition) {
        return null;
    }
    
    @Override
    public Pager<RawRequisitionSn> findListByRequestionNo(int page, int rows, RawRequisitionSn rawRequisitionSn){
    	long size = rawRequisitionSnMapper.queryCount(rawRequisitionSn);
        Pager<RawRequisitionSn> pager = new Pager<>();
        List<RawRequisitionSn> result = new ArrayList<>();
        pager.setPage(page);
        pager.setRows(rows);
        if (size > 0) {
            result = rawRequisitionSnMapper.queryList(pager, rawRequisitionSn);
        }
        pager.setRecords(result);
        pager.setTotalCount(size);
        return pager;
    }
    
    @Override
    public RawRequisition queryByRequestionId (RawRequisition rawRequisition){
    	return outWhRawMapper.queryById(rawRequisition);
    }
    
    
    /**  
     * @Title: confirmRequisitionNo
     * @Description:   确认时判断数据是否合规
     * @author Lengxf  
     * @date 2019年2月25日    
     */  
    @Override 
    @Transactional
    public TransResult confirmRequisitionNo(RawRequisition rawRequisition){
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
    	
    	RawRequisition entity = outWhRawMapper.queryById(rawRequisition);
    	List<BaseDictionary> fuliaoList = baseDictionaryMapper.queryFuliaoList();
    	
    	if(entity.getRequisitionStatus() != null 
    			&& !"0".equals(entity.getRequisitionStatus()) 
    			&& !"1".equals(entity.getRequisitionStatus()) ){
    		//领料单状态：0 新建状态 1 发货中
    		result.setMsg("该领料单当前状态无法进行领料出库操作");
    		result.setCode(Constant.FAIL);
    		return result;
    	}else if(entity.getRequisitionType() != null
    				&& !"3".equals(entity.getRequisitionType()) 
    				&& !"4".equals(entity.getRequisitionType()) ){
    		//领料单类型： 3 辅料 4补料
    		result.setMsg("只有“辅料”类型的物料才可进行出库确认操作");
    		result.setCode(Constant.FAIL);
    		return result;
    	}else if(entity.getRequisitionType() != null && "4".equals(entity.getRequisitionType())) {
    			
        		//补料的领料单，判定物料为辅料
        		boolean fuliaoFlag = true;
        		for(BaseDictionary bd : fuliaoList){
        			if(entity.getModelType().equals(bd.getDicCode())){
        				fuliaoFlag = false;
        			}
        		}
        		
        		if(fuliaoFlag){
        			result.setMsg("该补料单下的物料不是辅料");
        			result.setCode(Constant.FAIL);
        			return result;
    			}
		}
    	
    	BigDecimal newAmount = rawRequisition.getRealAmount() == null ? BigDecimal.ZERO : rawRequisition.getRealAmount();
		BigDecimal oldAmount = entity.getRealAmount() == null ? BigDecimal.ZERO : entity.getRealAmount();
		
		BigDecimal addAmount = newAmount.subtract(oldAmount);
		
		if(addAmount.compareTo(BigDecimal.ZERO) > 0) {
			RawStorageSn snTmp = new RawStorageSn();
			snTmp.setModel(entity.getModel());
			snTmp.setActiveFlag("1");
			RawStorageSn ttt = rawStorageSnMapper.querySumAmount(snTmp);
			
			BigDecimal storageAmount = ttt.getAmount() == null ? BigDecimal.ZERO : ttt.getAmount();
			
			if(storageAmount.compareTo(addAmount) < 0) {
				result.setMsg("该型号可用库存不足！");
    			result.setCode(Constant.FAIL);
    			return result;
			}
		}
    	
    	return result;
    }
    
    
    /**  
     * @Title: confirmRequisitionNoUpdate
     * @Description:   回传mes成功后进行数据修改
     * @author Lengxf  
     * @date 2019年2月25日    
     */  
    @Override
    @Transactional
    public TransResult confirmRequisitionNoUpdate(RawRequisition rawRequisition, String loginName){
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
    	
    	Date now = new Date();
    	
    	RawRequisition entity = outWhRawMapper.queryById(rawRequisition);
		//更新当前领料单状态
		entity.setRealAmount(rawRequisition.getRealAmount());
		entity.setRequisitionStatus("1");
		entity.setGmtModified(now);
		entity.setLastModifiedBy(loginName);
		outWhRawMapper.updateBySelect(entity);
		
		RawRequisitionSn thisSn = new RawRequisitionSn();
		thisSn.setRequisitionId(entity.getRequisitionId());//领料主表主键确定为一条明细
		List<RawRequisitionSn> reSnList = rawRequisitionSnMapper.queryByAny(thisSn);
		if(reSnList != null && reSnList.size() > 0){
			//如果存在记录则在原始记录上进行修改
			RawRequisitionSn updateReSn = reSnList.get(0);
			updateReSn.setAmount(rawRequisition.getRealAmount());
			updateReSn.setUnit(entity.getUnit());
			updateReSn.setLastModifiedBy(loginName);
			updateReSn.setGmtModified(now);
			rawRequisitionSnMapper.updateBySelect(updateReSn);
		}else{
			//如果不存在记录则向领料明细表插入辅料确认明细
    		RawRequisitionSn rawRequisitionSn = new RawRequisitionSn();
    		rawRequisitionSn.setRequisitionId(entity.getRequisitionId());
    		rawRequisitionSn.setRequisitionNo(entity.getRequisitionNo());
    		rawRequisitionSn.setRequisitionType(entity.getRequisitionType());
    		rawRequisitionSn.setModelDesc(entity.getModelDesc());
    		rawRequisitionSn.setContractNo(entity.getContractNo());
    		rawRequisitionSn.setBarcode(" ");
//    		//mes标志位：  0未上传  1已上传
//    		rawRequisitionSn.setMesStatus("0");
    		rawRequisitionSn.setModel(entity.getModel());
    		rawRequisitionSn.setModelDesc(entity.getModelDesc());
    		rawRequisitionSn.setModelType(entity.getModelType());
    		rawRequisitionSn.setUnit(entity.getUnit());
    		rawRequisitionSn.setAmount(rawRequisition.getRealAmount());
    		rawRequisitionSn.setBackAmount(BigDecimal.ZERO);
    		rawRequisitionSn.setGmtCreate(new Date());
    		rawRequisitionSn.setCreateBy(loginName);
    		rawRequisitionSn.setActiveFlag("1");
    		//rawRequisitionSn.setWlCode(entity.getUserDefined2());
    		rawRequisitionSnMapper.create(rawRequisitionSn);
		}
		    		
		RawStorageSn thisStroSn = new RawStorageSn();
		thisStroSn.setUserDefined5(entity.getRequisitionId().toString()); //备用字段5存放 领料单主表主键，实现物理主键关联
		List<RawStorageSn> srtoSnList = rawStorageSnMapper.queryByAny(thisStroSn);
		if(srtoSnList != null && srtoSnList.size() > 0){
			//判断库存明细表里是否有数据，若有则在原始数据进行修改
			RawStorageSn updateStroSn = srtoSnList.get(0);
			updateStroSn.setAmount(rawRequisition.getRealAmount().negate());
			updateStroSn.setGmtModified(now);
			updateStroSn.setUnit(entity.getUnit());
			updateStroSn.setLastModifiedBy(loginName);
			rawStorageSnMapper.updateBySelect(updateStroSn);
		}else{
    		//若没有数据则记录新的库存记录
    		RawStorageSn rawStorageSn = new RawStorageSn();
    		rawStorageSn.setContractNo(entity.getContractNo());
    		rawStorageSn.setBarcode(" ");
    		rawStorageSn.setModel(entity.getModel());
    		rawStorageSn.setRequisitionType(entity.getRequisitionType());
    		rawStorageSn.setModelDesc(entity.getModelDesc());
    		rawStorageSn.setModelType(entity.getModelType());
    		rawStorageSn.setUserDefined3("0");
    		rawStorageSn.setUserDefined2(" ");
    		rawStorageSn.setUserDefined5(entity.getRequisitionId().toString());//库存明细关联领料表主键
    		rawStorageSn.setUnit(entity.getUnit());
    		rawStorageSn.setAmount(rawRequisition.getRealAmount().negate());
    		rawStorageSn.setBarcodeStatus("0");
    		//rawStorageSn.setWlCode(entity.getUserDefined2());
    		rawStorageSn.setGmtCreate(now);
    		rawStorageSn.setCreateBy(loginName);			
    		rawStorageSn.setActiveFlag("1");
    		rawStorageSn.setIsAccessories("0");
    		rawStorageSn.setOutType("1");
    		rawStorageSn.setRequisitionNo(entity.getRequisitionNo());
    		rawStorageSnMapper.create(rawStorageSn);
		}
		
    	
    	return result;
    }
    
    @Override
    public TransResult closeRequestionNo (RawRequisition rawRequisition,String loginName){
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
    	
    	RawRequisition entity = outWhRawMapper.queryById(rawRequisition);
    	
    	if(!"1".equals(entity.getRequisitionStatus())){
    		result.setCode(Constant.FAIL);
    		result.setMsg("只有状态为“发货中”的领料单才可进行关闭操作");
    		return result;
    	}else if(!"3".equals(entity.getRequisitionType()) 
    			&& !"4".equals(entity.getRequisitionType())){
    		result.setCode(Constant.FAIL);
    		result.setMsg("只有“辅料”类型的物料才可进行关闭操作");
    		return result;
    	}else{
			if("4".equals(entity.getRequisitionType())){
    		//补料的领料单，判定物料为辅料
    		List<BaseDictionary> fuliaoList = baseDictionaryMapper.queryFuliaoList();
    		
    		boolean fuliaoFlag = false;
    		for(BaseDictionary bd : fuliaoList){
    			if(entity.getModelType().equals(bd.getDicCode())){
    				fuliaoFlag = true;
    				}
    			}
    		if(!fuliaoFlag){
				result.setMsg("该补料单下的物料不是辅料");
				result.setCode(Constant.FAIL);
				return result;
				}
			}
    		entity.setGmtModified(new Date());
    		entity.setLastModifiedBy(loginName);
    		outWhRawMapper.closeRequestionNoById(entity);
    	}
    	
    	return result;
    }
    
    @Override
    public List<RawRequisitionSn> queryRequisitionById(RawRequisitionSn rawRequisitionSn){
    	return rawRequisitionSnMapper.queryRequisitionById(rawRequisitionSn);
    }
    
    
}
